﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Acms.Bll;
using System.Text;

/// <summary>
/// Summary description for BaseTemplatePage
/// </summary>
public abstract class BaseTemplatePage : BasePage
{
    public BaseTemplatePage()
    {
    }

    protected override void OnPreLoad(EventArgs e)
    {
        base.OnPreLoad(e);
        if (!IsPostBack)
        {
            if (Request.QueryString["Id"] != null)
            {
                try
                {
                    TemplateId = int.Parse(Request.QueryString["Id"]);
                }
                catch
                {
                }
            }
        }
    }

    public override Acms.Bll.Role.Roles[] AllowedRoles
    {
        get { return new Role.Roles[] { Role.Roles.Developer}; }
    }

    private int _templateId;
    protected int TemplateId
    {
        get
        {
            return _templateId;
        }
        set
        {
            _templateId = value;
            _CurrentTemplate = null;
        }
    }

    protected override object SaveViewState()
    {
        ViewState["TemplateId"] = TemplateId;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        if (ViewState["TemplateId"] is int)
        {
            TemplateId = (int)ViewState["TemplateId"];
        }
    }

    private Template _CurrentTemplate;
    public Template CurrentTemplate
    {
        get
        {
            if(_CurrentTemplate == null && TemplateId > 0)
            {
                _CurrentTemplate = Template.GetById(TemplateId);
            }
            return _CurrentTemplate;
        }
    }

    public string AppendQueryString(string url)
    {
        if(url == null)
        {
            return null;
        }
        StringBuilder tmp = new StringBuilder();
        if(url.Contains("?Id="))
        {
            tmp.Append(url.Substring(0, url.IndexOf("?Id=")));
        }
        else if (url.Contains("&Id="))
        {
            tmp.Append(url.Substring(0, url.IndexOf("&Id=")));
        }
        else
        {
            tmp.Append(url);
        }

        if (tmp.ToString().Contains("?"))
        {
            tmp.Append("&");
        }
        else
        {
            tmp.Append("?");
        }
        tmp.AppendFormat("Id={0}", TemplateId);
        return tmp.ToString();
    }

    public override void GetBreadCrumbs(BaseMasterPage.BreadCrumbCollection breadcrumbs)
    {
        breadcrumbs.Add("Settings", null);
        breadcrumbs.Add("Templates", "~/Templates");
        if (this.CurrentTemplate != null)
        {
            breadcrumbs.Add(CurrentTemplate.Name, string.Format("~/Templates/Default.aspx?Id={0}", this.CurrentTemplate.Id));
        }
    }
}
